package com.mantru.iotpot.job;

import android.os.Bundle;
import android.os.Message;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.eventbus.EventMessage;
import com.mantru.iotpot.modbus.Common;
import com.mantru.iotpot.RegisterBuffer;
import com.mantru.iotpot.modbus.ModbusFunction;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * 任务管理主类
 */
public class JobMaster {
    //任务状态常量
    public static int JOB_STATUS_STOP = 1;       //停止
    public static int JOB_STATUS_RUN = 2;        //执行中
    public static int JOB_STATUS_SUSPEND = 3;    //暂停
    public static int JOB_STATUS_POURWATER = 4;  //倒水
    public static int JOB_STATUS_GOTOCOOKPLACE = 5;  //回到炒菜位
    //烹饪专用状态，10已结束、20烹饪中、21烹饪中+手动投料中、25复炒中、29烹饪完成（未出菜）、30暂停中、31暂停中+确认投料中、40出菜中
    public static int JOB_STATUS_COOKING_Dialog1 =21;   //烹饪中+手动投料中
    public static int JOB_STATUS_COOKING_Dialog2 =31;   //暂停中+确认投料中
    public static int JOB_STATUS_COOKING_RESUME = 25;   //复炒中
    public static int JOB_STATUS_COOKING_PourOut = 40;  //出菜中
    //任务结点类型
    public static int JOB_NODE_TYPE_BEGIN = 0;   //0开始时固定执行的指令
    public static int JOB_NODE_TYPE_END = 1;     //1结束时固定执行的指令
    public static int JOB_NODE_TYPE_USER = 2;    //2用户自定义的常规指令
    //定时器间隔，每隔200ms触发1次
    public static int TIMER_INTERVAL = 200;
    //暂停最长时间，60秒
    public static int SUSPEND_MAX_INTERVAL = 60000;
    //每隔2秒读一次红外温度
    public static  int Temperature_READ_INTERVAL = 2000;
    //每隔1秒读一次错误码
    public static  int ERROR_READ_INTERVAL = 1000;
    //每隔1秒读一次全部地址  2023.12.12 从3秒改为1秒
    public static  int ALL_ADDRESS_READ_INTERVAL = 1000;

    //全局变量
    private ApplicationClass ac;
    public String job_name = "";                 //任务名称，clean_auto自动清洗、clean_hand/clean_hand_new手动清洗、pour_water倒水/出菜、goto_cook_place回到炒菜位、cooking_system烹饪系统菜谱、cooking_my烹饪我的菜谱、cooking_cloud烹饪云端菜谱、cooking_resume复炒、set_param_value设置系统参数、feed_pot一键养锅
    public int job_status = JOB_STATUS_STOP;     //任务状态，初始为停止
    public ArrayList<JobSteep> steep_list;       //任务步骤队列
    public ArrayList<JobNode> job_list_all;      //任务全部步骤指令队列
    public ArrayList<JobNode> job_list_has_run;  //已执行的步骤指令队列（含执行中）
    public ArrayList<JobNode> job_list_stop;     //结束任务时必须归0指令队列
    public ArrayList<JobNode> job_list_suspend;  //暂停任务时必须归0指令队列
    public ArrayList<JobNode> job_list_start;    //启动任务时必须恢复的指令队列（指从暂停状态启动的时候）
    public ArrayList<JobNode> job_list_pourwater;//倒水指令队列
    public ArrayList<JobRegister> register_list; //任务中已执行步骤指令中用到的寄存器的列表
    public RegisterBuffer register_buffer;       //4大寄存器暂停前的值
    public int current_job_index = -1;           //当前执行的任务序号，是指job_list_all队列的序号，从0开始，-1表示未开始执行
    public int current_stop_index = -1;          //任务结束时要执行的序号，是指job_list_stop队列的序号，从0开始，-1表示未开始执行
    public int current_suspend_index = -1;       //任务暂停时要执行的序号，是指job_list_suspend队列的序号，从0开始，-1表示未开始执行
    public int current_start_index = -1;         //任务启动时要执行的序号，是指job_list_start队列的序号，从0开始，-1表示未开始执行
    public int steep_count = 0;                  //步骤总数量
    public int steep_index = 0;                  //当前执行的步骤序号，从1开始，0表示未开始执行
    public int time_long = 0;                    //总时长，单位：秒
    public long time_pass = 0;                   //已执行的时长，单位：ms，该值从0开始
    public long time_pass_suspend = 0;           //暂停的时长，单位：ms，该值从0开始
    public int fire_value = 0;                   //档位，0-9档，值越大表示火力越大
    public int speed_value = 0;                  //转速，0停、1慢、2中、3快
    public int rotation_value = 0;               //锅转向，1逆时针、2顺时针（协议值：0是顺时针、1是逆时针）
    public int dialog1_time_long = 0;            //弹出手动投料倒计时dialog1的最大值，默认30秒
    public int dialog2_time_long = 0;            //弹出未确认投料确认dialog2的最大值，默认60秒
    public long com_last_send_time = 0;          //串口最后一次发送的时间，单位：ms
    public long com_last_receive_time = 0;       //串口最后一次接收的时间，单位：ms
    public boolean is_need_read_temperature = false;  //是否需要加插发送读红外温度指令，true是
    public boolean is_need_read_errorcode = false;    //是否需要加插发送读错误码指令，true是
    public boolean is_need_read_pump = false;         //是否需要加插发送读三只泵状态指令，true是
    public boolean is_need_record = false;            //是否需要录制，true是


    public JobMaster(ApplicationClass ac, String job_name, int steep_count){
        this.ac = ac;
        this.job_name = job_name;
        this.steep_count = steep_count;
        steep_list = new ArrayList<JobSteep>();
        job_list_all = new ArrayList<JobNode>();
        job_list_has_run = new ArrayList<JobNode>();
        register_list = new ArrayList<JobRegister>();
        job_list_stop = new ArrayList<JobNode>();
        job_list_suspend = new ArrayList<JobNode>();
        job_list_start = new ArrayList<JobNode>();
        job_list_pourwater = new ArrayList<JobNode>();
        register_buffer = new RegisterBuffer();
    }

    //添加一个任务指令结点（无时间触发器）
    public void AddJobNode(int node_type, int steep_index, int slave, int function_code, int starting_address, int quantity_of_x, int output_value, boolean is_need_init, int init_value){
        JobNode node = new JobNode(node_type, steep_index, slave, function_code, starting_address, quantity_of_x, output_value, is_need_init, init_value, 0);
        job_list_all.add(node);
    }
    //添加一个任务指令结点（有时间触发器），timer_trigger_value是发送指令后多少ms就触发关闭指令
    public void AddJobNode(int node_type, int steep_index, int slave, int function_code, int starting_address, int quantity_of_x, int output_value, boolean is_need_init, int init_value, int timer_trigger_value){
        JobNode node = new JobNode(node_type, steep_index, slave, function_code, starting_address, quantity_of_x, output_value, is_need_init, init_value, timer_trigger_value);
        job_list_all.add(node);
    }

    //添加一个步骤
    public void AddSteep(int steep_type, int steep_index, int pot_position, int fire_value, String time_value, int time_long, int speed_value, int rotation_value, int status, String tts_text){
        JobSteep steep = new JobSteep(steep_type, steep_index, pot_position, fire_value, time_value, time_long, speed_value, rotation_value, status, tts_text);
        steep_list.add(steep);
    }

    //启动作业
    public void Start() {
        if (job_status == JOB_STATUS_RUN)
            return;
        //启动之前处于停止状态
        if (job_status == JOB_STATUS_STOP) {
            //初始化一些全局变量
            current_job_index = -1;
            steep_index = 1;
            time_pass = 0;
            time_pass_suspend = 0;
            job_list_has_run.clear();
            register_list.clear();
            job_list_stop.clear();
            job_list_suspend.clear();
            job_list_start.clear();
            job_list_pourwater.clear();
            //步骤队列计时清零
            for (int i = 0; i < steep_list.size(); i++) {
                JobSteep steep = steep_list.get(i);
                steep.begin_time = 0;
                steep.end_time = 0;
                steep.pass_time = 0;
            }
            //第1步骤开始计时
            JobSteep steep = steep_list.get(steep_index - 1);
            steep.begin_time = Common.GetTimeStamp13();
        }
        //启动之关处于暂停状态
        if (job_status == JOB_STATUS_SUSPEND) {
            //将暂停时发送的指令恢复
            time_pass_suspend = 0;
            job_list_stop.clear();
            job_list_start.clear();
            current_start_index = -1;
            //2023.09.02 暂停后再恢复工作，马上设置4个寄存器的值
            try {
                ac.com.writeSingleRegister(0x01, 0x0010, register_buffer.register_0x0010, this);
                ac.com.writeSingleRegister(0x01, 0x0011, register_buffer.register_0x0011, this);
                ac.com.writeSingleRegister(0x01, 0x0015, register_buffer.register_0x0015, this);
            }catch (Exception ex)
            {}
            /*
            for (int i=0; i < job_list_suspend.size(); i++) {
                JobNode node1 = job_list_suspend.get(i);
                JobNode node2 = new JobNode(JOB_NODE_TYPE_USER, 1, node1.slave, node1.function_code, node1.starting_address, node1.quantity_of_x, node1.init_value, true, node1.output_value, 0);
                job_list_start.add(node2);
                //Log("从暂停恢复运行：starting_address=" + node1.starting_address + ",function_code=" + node1.function_code + ",value=" + node1.init_value);
            }
            job_list_suspend.clear();
            */
        }
        //开始执行1条指令
        job_status = JOB_STATUS_RUN;
        RunNextStart();
    }

    //强行读温度
    public void ReadTemperature()
    {
        long now = Common.GetTimeStamp13();
        if (is_need_read_temperature == true && (now - com_last_receive_time) >= Temperature_READ_INTERVAL)
            RunNextStart();
    }

    //从队列中取出1条指令并执行
    private void RunNextStart(){
        if (job_status != JOB_STATUS_RUN)
            return;
        //加插发送读取红外温度
        if (is_need_read_temperature == true) {
            is_need_read_temperature = false;
            com_last_send_time = Common.GetTimeStamp13();
            ac.com.ReadHoldingRegister(0x01, 0x003C, 0x0001);
            return;
        }
        //加插发送读取故障码
        if (is_need_read_errorcode == true) {
            is_need_read_errorcode = false;
            com_last_send_time = Common.GetTimeStamp13();
            ac.com.ReadHoldingRegister(0x01, 0x0003, 0x0008);
            return;
        }
        //优先执行从暂停后启动的指令队列
        if (job_list_start.size() > 0) {
            current_start_index++;
            if (current_start_index < job_list_start.size()) {
                try {
                    JobNode node = job_list_start.get(current_start_index);
                    //写寄存器
                    if (node.function_code == ModbusFunction.WRITE_SINGLE_REGISTER) {
                        com_last_send_time = Common.GetTimeStamp13();
                        ac.com.writeSingleRegister(node.slave, node.starting_address, node.output_value, this);
                    }
                    //记录必须恢复归0状态的寄存器的值
                    UpdateRegisterValue(node);
                }catch (Exception ex){
                }
                return;
            }else {
                job_list_start.clear();
            }
        }

        //向串口发送1条指令
        current_job_index++;
        if (current_job_index < job_list_all.size()) {
            try {
                JobNode node = job_list_all.get(current_job_index);
                //加入已执行队列
                job_list_has_run.add(node);
                com_last_send_time = Common.GetTimeStamp13();
                if (node.function_code == ModbusFunction.WRITE_SINGLE_REGISTER)   //写寄存器
                    ac.com.writeSingleRegister(node.slave, node.starting_address, node.output_value, this);
                if (node.function_code == ModbusFunction.READ_HOLDING_REGISTERS)  //读寄存器
                    ac.com.ReadHoldingRegister(node.slave, node.starting_address, node.quantity_of_x);
                //记录必须恢复归0状态的寄存器的值
                UpdateRegisterValue(node);
                //启动触发器，主要是关闭四个水泵
                if (node.timer_trigger_value > 0) {
                    TimerTriggerThread trigger = new TimerTriggerThread(ac, node.timer_trigger_value, node.function_code, node.starting_address, node.init_value);
                    trigger.start();
                }
            }catch (Exception ex){
            }
        }
    }
    //更新寄存器的最新的值
    private void UpdateRegisterValue(JobNode node){
        if (node.function_code != ModbusFunction.WRITE_SINGLE_REGISTER)
            return;
        for (int i=0; i < register_list.size(); i++)
        {
            JobRegister register = register_list.get(i);
            if (register.starting_address == node.starting_address)
            {
                register.quantity_of_x = node.quantity_of_x;
                register.current_value = node.output_value;
                register.is_need_init = node.is_need_init;
                register.init_value = node.init_value;
                return;
            }
        }
        JobRegister register = new JobRegister(node.node_type, node.slave, node.function_code, node.starting_address, node.quantity_of_x, node.output_value, node.is_need_init, node.init_value);
        register_list.add(register);
    }


    //停止作业
    public void Stop(){
        if (job_status == JOB_STATUS_STOP)
            return;
        job_list_stop.clear();
        //计算需要归0的寄存器
        for (int i=0; i < register_list.size(); i++)
        {
            JobRegister register = register_list.get(i);
            if (register.is_need_init && register.current_value != register.init_value)
            {
                JobNode node = new JobNode(register.node_type, 1, register.slave, register.function_code, register.starting_address, register.quantity_of_x, register.init_value, false, 0, 0);
                job_list_stop.add(node);
            }
        }
        //计算任务结束时固定要执行的指令
        for (int i=0; i < job_list_all.size(); i++)
        {
            JobNode node = job_list_all.get(i);
            if (node.node_type == JOB_NODE_TYPE_END)
                job_list_stop.add(node);
        }
        /*2023.08.03  炒菜、录制、试炒、手动清洗，这四个任务停止时用写入多个寄存器的办法停止
        转速：0x0010   写  0x00   停
        转向：0x0011   写  0x00   顺时针
             0x0012   写  0x00
        锅位：0x0013   写  0xFF
             0x0014   写  0x00
        档位：0x0015   写  0x00   0档
        */
        if (job_name.contains("cooking") || job_name.contains("clean_hand_new")) {
            job_list_stop.clear();
            try {
                int[] data = {0x00, 0x00, 0x00, 0xFF, 0x00, 0x00};
                ac.com.writeHoldingRegisters(0x01, 0x0010, 6, data);  //写一次
                ac.com.writeHoldingRegisters(0x01, 0x0010, 6, data);  //再写一次，保险起见
                data = null;
            }catch (Exception ex){
            }
        }

        current_stop_index = -1;
        job_status = JOB_STATUS_STOP;
        RunNextStop();
    }
    //从结束队列中取出1条指令并执行
    private void RunNextStop(){
        if (job_status == JOB_STATUS_RUN)
            return;
        //向串口发送1条指令
        current_stop_index++;
        if (current_stop_index < job_list_stop.size()) {
            try {
                JobNode node = job_list_stop.get(current_stop_index);
                if (node.function_code == ModbusFunction.WRITE_SINGLE_REGISTER) {   //写寄存器
                    com_last_send_time = Common.GetTimeStamp13();
                    ac.com.writeSingleRegister(node.slave, node.starting_address, node.output_value, this);
                }
            }catch (Exception ex){
            }
        }else{
            //清除队列表示已彻底结束
            job_list_stop.clear();
        }
    }

    //暂停作业
    public void Suspend(){
        if (job_status != JOB_STATUS_RUN)
            return;
        job_list_suspend.clear();
        //计算需要归0的寄存器
        //Log("register_list.size()=" + register_list.size());
        for (int i=0; i < register_list.size(); i++)
        {
            JobRegister register = register_list.get(i);
            if (register.is_need_init && register.current_value != register.init_value)
            {
                JobNode node = new JobNode(register.node_type, 1, register.slave, register.function_code, register.starting_address, register.quantity_of_x, register.init_value, false, register.current_value, 0);
                job_list_suspend.add(node);
                if (register.starting_address == 0x0010) register_buffer.register_0x0010 = register.current_value;
                if (register.starting_address == 0x0011) register_buffer.register_0x0011 = register.current_value;
                if (register.starting_address == 0x0012) register_buffer.register_0x0012 = register.current_value;
                if (register.starting_address == 0x0013) register_buffer.register_0x0013 = register.current_value;
                if (register.starting_address == 0x0014) register_buffer.register_0x0014 = register.current_value;
                if (register.starting_address == 0x0015) register_buffer.register_0x0015 = register.current_value;
            }
        }
        time_pass_suspend = 0;
        current_suspend_index = -1;
        job_status = JOB_STATUS_SUSPEND;
        RunNextSuspend();
    }
    //从暂停队列中取出1条指令并执行
    private void RunNextSuspend(){
        if (job_status != JOB_STATUS_SUSPEND)
            return;
        //向串口发送1条指令
        current_suspend_index++;
        if (current_suspend_index < job_list_suspend.size()) {
            try {
                JobNode node = job_list_suspend.get(current_suspend_index);
                if (node.function_code == ModbusFunction.WRITE_SINGLE_REGISTER) {   //写寄存器
                    com_last_send_time = Common.GetTimeStamp13();
                    ac.com.writeSingleRegister(node.slave, node.starting_address, node.output_value, this);
                }
            }catch (Exception ex){
            }
        }
    }

    //继续作业（由暂停状态恢复）
    public void Continue(){
        //Log("job_status=" + job_status);
        if (job_status != JOB_STATUS_SUSPEND)
            return;
        Start();
    }

    //下一步骤
    public void NextSteep(){
        if (job_status != JOB_STATUS_RUN)
            return;
        //当前步骤对象
        JobSteep steep = steep_list.get(steep_index - 1);
        steep.end_time = Common.GetTimeStamp13();
        //执行下一个步骤
        if (steep_index < steep_count) {
            steep_index++;
            //Log("steep_index=" + steep_index);
            JobSteep steep2 = steep_list.get(steep_index - 1);
            steep2.begin_time = Common.GetTimeStamp13();
            RunNextStart();
            //TTS播报语音
            if (steep2.tts_text.length() > 0){
                String msg = "{\"text\":\""+steep2.tts_text+"\"}";
                EventMessage e = new EventMessage(EventMessage.MSG_ID_TTSSpeak, msg);
                EventBus.getDefault().post(e);
            }
            //Log("end");
            return;
        } else {
            //总计时结束，任务执行完毕
            Stop();
            return;
        }

    }


    //定时器事件，由外部定时器线程触发，TIMER_INTERVAL是触发的时间隔，单位ms
    public void OnTimer(){
        try {
            /* 2023.09.02  暂停倒计时不需要了，交给UI前端去计算
            //暂停倒计时
            if (job_status == JOB_STATUS_SUSPEND) {
                time_pass_suspend += TIMER_INTERVAL;
                if (time_pass_suspend >= SUSPEND_MAX_INTERVAL)
                    Stop();
                return;
            }
            */
            if (job_status == JOB_STATUS_STOP || job_status == JOB_STATUS_SUSPEND)
                return;

            //2023.01.06 只有清洗模式、一键养锅模式下需要计算时间，烹饪模式下由H5前端计算时间
            if (job_name.startsWith("cooking") == false) {
                //全局计时变量
                time_pass += TIMER_INTERVAL;
                //步骤内部计时变量
                JobSteep steep = steep_list.get(steep_index - 1);
                steep.pass_time += TIMER_INTERVAL;

                //当前步骤计时执行完毕
                if (steep.pass_time >= steep.time_long * 1000) {
                    steep.end_time = Common.GetTimeStamp13();
                    //执行下一个步骤
                    if (steep_index < steep_count) {
                        steep_index++;
                        JobSteep steep2 = steep_list.get(steep_index - 1);
                        steep2.begin_time = Common.GetTimeStamp13();
                        RunNextStart();
                        return;
                    } else {
                        //总计时结束，任务执行完毕
                        Stop();
                        return;
                    }
                }
            }
        }
        catch (Exception ex)
        {}
    }

    /**
     * 串口收到的数据进行解码
     * @param data 收到的数据
     * @param read_address 读取的地址
     * @param read_len 读取数据长度
     */
    public void OnComData(String data, int read_address, int read_len){
        com_last_receive_time = Common.GetTimeStamp13();
        //任务处于结束状态，但是要执行寄存器归0指令
        if (job_status == JOB_STATUS_STOP && job_list_stop.size() > 0)
        {
            RunNextStop();
            return;
        }
        //任务处于暂停状态，但是要执行寄存器归0指令
        if (job_status == JOB_STATUS_SUSPEND && job_list_suspend.size() > 0)
        {
            RunNextSuspend();
            return;
        }
        if (job_status != JOB_STATUS_RUN)
            return;
        //从指令队列中取出1条当前步骤的余下指令
        int index = current_job_index + 1;
        if (index < job_list_all.size())
        {
            JobNode node = job_list_all.get(index);
            if (node.steep_index == steep_index && node.node_type != JobMaster.JOB_NODE_TYPE_END)
                RunNextStart();
        }
        //最后一次，还需要读温度的情况
        if (index == job_list_all.size() && is_need_read_temperature == true)
        {
            RunNextStart();
        }
        //2023.07.14 暂停恢复后要执行一些指令
        if (job_list_start.size() > 0 && current_start_index < job_list_start.size())
        {
            RunNextStart();
        }
        //读取三只泵的状态回复，再启动触发器300ms后再读一次
        if (read_address == 0x000B && is_need_read_pump == true)
        {
            TimerTriggerThread trigger = new TimerTriggerThread(ac, 300, 0x03, 0x000B, 0);
            trigger.start();
        }
    }

    /**
     * 收到触发器，实现定时给四个泵发关闭指令
     * @param data 收到的数据
     * data={"timer_interval":"2000", "function_code":"6", "register_address":"22", "output_value":"0"}
     */
    public void OnTrigger(String data) {
        int function_code = Integer.parseInt(Common.JSON_GetFieldValue(data, "function_code"));
        int register_address = Integer.parseInt(Common.JSON_GetFieldValue(data, "register_address"));
        int output_value = Integer.parseInt(Common.JSON_GetFieldValue(data, "output_value"));

        //任务处于结束状态，但是要执行寄存器归0指令
        if (job_status == JOB_STATUS_STOP) {
            //2023.04.07 在这里强行写入串口指令，关闭喷水/汕
            if (function_code == ModbusFunction.WRITE_SINGLE_REGISTER) {
                try {
                    ac.com.writeSingleRegister(0x01, register_address, output_value, null);
                }catch (Exception ex){
                }
            }
            return;
        }
        try {
            //创建新的结点
            int len = 0x01;
            if (register_address == 0x000B)   //读泵的地址要读三个泵
                len = 0x03;
            JobNode node = new JobNode(JobMaster.JOB_NODE_TYPE_USER, steep_index, 0x01, function_code, register_address, len, output_value, false, 0, 0);
            //加入已执行队列
            job_list_has_run.add(node);
            com_last_send_time = Common.GetTimeStamp13();
            if (node.function_code == ModbusFunction.WRITE_SINGLE_REGISTER)   //写寄存器
                ac.com.writeSingleRegister(node.slave, node.starting_address, node.output_value, this);
            if (node.function_code == ModbusFunction.READ_HOLDING_REGISTERS)  //读寄存器
                ac.com.ReadHoldingRegister(node.slave, node.starting_address, node.quantity_of_x);
            //记录必须恢复归0状态的寄存器的值
            UpdateRegisterValue(node);
        }catch (Exception ex){
        }
    }

    //获取当前步骤总时长，单位：秒
    public int GetSteep_time_long(){
        if (steep_index > 0 && steep_index <= steep_list.size()) {
            JobSteep steep = steep_list.get(steep_index - 1);
            return steep.time_long;
        }
        return 0;
    }
    //获取当前步骤总时长，单位：秒
    public int GetSteep_time_pass(){
        if (steep_index > 0 && steep_index <= steep_list.size()) {
            JobSteep steep = steep_list.get(steep_index - 1);
            int time_pass = (int)(steep.pass_time / 1000);
            if (time_pass > steep.time_long)
                time_pass = steep.time_long;
            return time_pass;
        }
        return 0;
    }

    public void Log(String value)
    {
        String DeviceID = ac.activity_device_id;
        new Thread() {
            @Override
            public void run() {
                int error_code = 0;      //0表示没有发生异异，1表示有异常
                try
                {
                    String api_url = Common.API_Server_Url + "?txt_type=/pot/save_log/&device_id=" + DeviceID + "&code=200&timestamp=" + Common.GetTimeStamp13() + "&data=" + URLEncoder.encode(value);
                    URL url = new URL(api_url);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    InputStream is = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder builder = new StringBuilder();
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                    is.close();
                    conn.disconnect();
                }
                catch(Exception ex)
                {}
            }
        }.start();
    }


}


